﻿using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Infrastructure;
using Domain;
using System.Linq;
using Rabbit.Infrastructure.Interface;
using MD5Hash;
using RabbitTeacebillty.API.Read.Application.Command;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;
using RabbitTraceability.API.Application.Utils;

namespace RabbitTeacebillty.API.Read.Application.CommandHandler
{
    /// <summary>
    /// 登录请求处理器，实现用户登录的基本校验逻辑。
    /// </summary>
    public class LoginQueryCommandHandlerd : IRequestHandler<UserQueryCommand, ApiResult<User>>
    {
        /// <summary>
        /// 用户仓储，用于数据库操作
        /// </summary>
        private readonly IBaseRepository<User> _userRepository;

        /// <summary>
        /// 构造函数，注入用户仓储
        /// </summary>
        /// <param name="userRepository">用户仓储接口</param>
        public LoginQueryCommandHandlerd(IBaseRepository<User> userRepository)
        {
            _userRepository = userRepository;
        }

        /// <summary>
        /// 处理登录请求，校验用户名和密码（密码用MD5加密比对）
        /// </summary>
        /// <param name="request">登录请求命令，包含用户名和密码</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>登录结果，ApiResult<User>，成功时Data为用户信息</returns>
        public async Task<ApiResult<User>> Handle(UserQueryCommand request, CancellationToken cancellationToken)
        {
            // 校验验证码
            string redisKey = $"hekaile:{request.Guid}";
            string? realCaptcha = RedisHelper.GetValue(redisKey);
            if (string.IsNullOrEmpty(realCaptcha) || !string.Equals(realCaptcha, request.Captcha, StringComparison.OrdinalIgnoreCase))
            {
                return new ApiResult<User>
                {
                    Success = false,
                    Code = RabbitTraceability.ResultCode.Error,
                    Message = "验证码错误",
                    Data = null
                };
            }

            // 对密码进行MD5加密
            string passwordHash = request.Password.GetMD5();
            // 查询数据库中是否存在匹配的用户
            var user = _userRepository.GetAll().FirstOrDefault(u => u.UserName == request.UserName && u.PasswordHash == passwordHash);
            if (user != null)
            {
                // 登录成功，返回用户信息
                return new ApiResult<User>
                {
                    Success = true,
                    Code = RabbitTraceability.ResultCode.Success,
                    Message = "登录成功",
                    Data = user
                };
            }
            else
            {
                // 登录失败，用户名或密码错误
                return new ApiResult<User>
                {
                    Success = false,
                    Code = RabbitTraceability.ResultCode.Error,
                    Message = "用户名或密码错误",
                    Data = null
                };
            }
        }

        
    }
} 